<template>
  <div class="homework" v-loading="homeworkLoading">
    <div v-if="entranceData && entranceData.length > 0">
      <div class="left">
        <div class="question" v-if="questionData">
          <div class="title">
            <div>
              <p>试题数量：{{ questionData.questionCount }}</p>
              <p>试题总分：{{ questionData.totalScore }}</p>
            </div>
            <div class="text-img"><img src="/src/assets/one-prepare/text-img.png" alt="点津问道标品" width="80"></div>
          </div>
          <div class="content">
            <div class="content-group">
              <p>名称：{{ questionData.title }}</p>
              <div class="release-time" v-if="entranceData && entranceData[0].status !== 1">
                <div>发布时间：</div>
                <div><el-radio v-model="releaseTime" label="0">立即发送</el-radio><el-radio v-model="releaseTime" label="1">自定义时间</el-radio></div>
              </div>
              <div class="custom-time" v-if="releaseTime === '1' || (entranceData && entranceData[0].status === 1)">
                <div>自定义时间：</div>
                <div v-if="entranceData && entranceData[0].status === 1"><el-date-picker  v-model="entranceData[0].startTime" type="datetime"  placeholder="截止时间" size="small" format="YYYY-MM-DD HH:mm:ss" :disabled="entranceData && entranceData[0].status === 1"></el-date-picker></div>
                <div v-else><el-date-picker v-model="form.startTime" type="datetime" placeholder="自定义时间" size="small" format="YYYY-MM-DD HH:mm:ss"></el-date-picker></div>
              </div>
              <div class="end-time">
                <div>截止时间：</div>
                <div v-if="entranceData && entranceData[0].status === 1"><el-date-picker  v-model="entranceData[0].endTime" type="datetime"  placeholder="截止时间" size="small" format="YYYY-MM-DD HH:mm:ss" :disabled="entranceData && entranceData[0].status === 1"></el-date-picker></div>
                <div v-else><el-date-picker  v-model="form.endTime" type="datetime"  placeholder="截止时间" size="small" format="YYYY-MM-DD HH:mm:ss"></el-date-picker></div>
              </div>
              <div class="student">
                <div>学生：</div>
                <div><span v-for="item in student" :key="item">{{ item.studentName}}</span></div>
              </div>
              <el-button class="submit" @click="submit" v-if="entranceData && entranceData[0].status !== 1">发布作业</el-button>
              <el-button class="submited" disabled v-if="entranceData && entranceData[0].status === 1">已发布</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <TestPaperPreview :previewNoRoute="true" :idNoRoute="entranceData[0].paperId"/>
      </div>
      <div class="btns">
        <div class="editQuestion" @click="editQuestion" ><img src="/src/assets/one-prepare/edit.png" alt=""></div>
        <div class="download" @click="downLoad" v-if="prepareData.status === 3"><i class="iconfont iconxiazai"></i></div>
      </div>
    </div>
    <div v-if="entranceData && entranceData.length === 0" class="noData">
      <div>
        <img src="/src/assets/one-prepare/no-data.png" alt="点津问道标品" width="475">
        <p>未添加作业，选择试卷添加</p>
        <el-button @click="addQuestion('testPaper')">添加试卷</el-button>
        <el-button @click="addQuestion('syncPaper')">添加同步练习试卷</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import $ from '$'
import store from './../../store'
import HandoutPreviewComponent from '@/views/handout/index.vue';
import TestPaperComponent from './testpaper.vue'
import TestPaperPreview from '@/views/test-paper/update/index.vue'
import downloadComponent from '@/views/test-paper/components/download.vue'
import SyncPaper from './sync-paper.vue'
import Moment from "moment";
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';

export default {
  components: { HandoutPreviewComponent, TestPaperPreview },
  setup () {
    let classData = computed(() => store.state.classData)
    let prepareData = computed(() => store.state.prepareData)
    let entranceData = ref()
    let questionData = ref()
    let student = ref()
    let releaseTime = ref('0')
    let getTimeId = null
    let form = reactive({
      startTime: '',
      endTime: ''
    })
    form.startTime = Moment(new Date()).format(`YYYY-MM-DD HH:mm:ss`)
    let homeworkLoading = ref(true)
    const request = async(refresh?) => {
      let lessonTimeId = null
      if (classData.value) { lessonTimeId = classData.value.id } else { lessonTimeId = prepareData.value.id }
      let res = await $.http.post('/admin/lessonHomework/query',{ lessonTimeId: lessonTimeId })
      if (res.result) {
        res.json.length && (getTimeId = res.json[0].id)
        entranceData.value = res.json
        if (!refresh && res.json.length > 0) {
          let questionRes = await $.http.post('/tiku/paper/getPaper',{ id: entranceData.value[0].paperId })
          questionRes.result && (questionData.value = questionRes.json)
          let studentRes = await $.http.post('/admin/lessonInfo/queryStudent', { lessonId: prepareData.value.lessonId, searchType: prepareData.value.type, id: prepareData.value.id })
          studentRes.result && (student.value = studentRes.json, homeworkLoading.value = false)
        } else {
          homeworkLoading.value = false
        }
      }
    }
    setTimeout(() => {
      request(false)
      watch(()=> form, (e)=>{
        form.startTime && (form.startTime = Moment(e.startTime).format(`YYYY-MM-DD HH:mm:ss`));
        form.endTime && (form.endTime = Moment(e.endTime).format(`YYYY-MM-DD HH:mm:ss`));
        $.http.post('/admin/lessonHomework/saveOrUpdate', { ...form, id: getTimeId })
      }, { immediate: false, deep: true})
    })
    let subjectId = ref()
    $.emitter.emit('effect', (id) => subjectId.value = id)
    const editQuestion = () => {
      if (!entranceData.value[0].duplicated) {
        $.http.post('/tiku/paper/copyPaper',{ paperId: entranceData.value[0].paperId }).then(res => {
          if (res.result) {
            request(true)
            $.http.post('/admin/lessonHomework/saveOrUpdate', { id: entranceData.value[0].id, paperId: res.json, duplicated: 1}).then((result) => {
              result.result && (getTimeId = result.json.id)
            })
            $.http.post('/admin/lessonInfo/saveOrUpdate', { id: prepareData.value.id, step: 2 })
            classData.value && $.http.post('/admin/lessonTimes/saveOrUpdate', { id: classData.value.id, checked: 1, lessonThirdId: prepareData.value.thirdId  })
            window.open(`./#/test-paper-edit/false/${res.json}`);
            request(false)
          }
        })
      } else {
        window.open(`./#/test-paper-edit/false/${entranceData.value[0].paperId}`);
      }
    }
    const __courseAddData = (data) => {
      let lessonTimeId = null
      if (classData.value) { lessonTimeId = classData.value.id} else { lessonTimeId = prepareData.value.id}
      $.http.post('/admin/lessonInfo/saveOrUpdate', { id: prepareData.value.id, step: 2 })
      classData.value && $.http.post('/admin/lessonTimes/saveOrUpdate', { id: classData.value.id, checked: 1, lessonThirdId: prepareData.value.thirdId }) //更新已备课 checked：1 已选中课次
      store.commit('set_direct_class', false)
      $.http.post('/admin/lessonHomework/saveOrUpdate',{ lessonTimeId: lessonTimeId, paperId: data.id }).then(res => {
        res.result && request(false)
      })
    }
    const addQuestion = (componentName) => {
      $.drawer.create({
        width: 820,
        zIndex: 2010,
        component: componentName == 'syncPaper' ? SyncPaper : TestPaperComponent,
        props: {
          subjectCode: subjectId.value,
          addData: (data) => __courseAddData(data),
        },
        footed: false,
      });
    }
    let userId = useStore().getters.userInfo.user.id;
    const submit = () => {
      let classStudents = [{
        id: student.value[0].groupId ? student.value[0].groupId: student.value[0].studentId,
        students: student.value.map(item => { return Object.assign({}, { 'id': item.studentId, name: item.studentName }) })
      }]
      let params = {
        ...form,
        classIds: prepareData.value.id,
        userId: userId,
        type: 2,
        title: questionData.value.title,
        classStudents: classStudents,
        paperId: entranceData.value[0].paperId,
        status: 1
      }
      if (!form.endTime) {
        ElMessage.warning('请填写截止时间！')
      } else {
        $.http.json('admin/practice/publishPractice', params).then(res => {
          if (res.result) {
            $.http.post('/admin/lessonHomework/saveOrUpdate',{ id: entranceData.value[0].id, status: 1 }).then(() => {
              request(false)
              ElMessage.success('发布成功！')
            })
          }
        })
      }
    }
    const downLoad = () => {
      $.modal.create({
        title: '下载试卷',
        width: 640,
        component: downloadComponent
      }).then((res: any) => {
        window.open(`${import.meta.env.VITE_APP_BASE_URL}/tiku/paper/downPaper?paperId=${ entranceData.value[0].paperId }&type=${ res.type }&templateId=${ res.templateId }&fileType=${ res.fileType }`);
      });
    }
    return { editQuestion, subjectId, request, entranceData, addQuestion, questionData, prepareData, student, submit, homeworkLoading, releaseTime, form, downLoad }
  }
}
</script>
<style lang="scss" scoped>
  :deep(.paper_container) {
    padding: 0;
    width: 100%;
  }
  :deep(.el-textarea__inner) {
    border: none;
    padding: 0;
  }
  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    background: #fff;
    color: inherit;
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__inner) {
    width: 200px;
  }
  .homework {
    display: flex;
    height: 100%;
    .noData {
      display: flex;
      text-align: center;
      width: 475px;
      margin: 0 auto;
      button {
        margin-top: 40px;
        color: #72b22a;
        border: 1px solid #72b22a;
        &:hover {
          color: #fff;
          background: #72b22a;
        }
      }
    }
    & > div {
      display: flex;
    }
    .left {
      padding: 0 20px 15px 0;
      .question {
        width: 230px;
        border-radius: 4px;
        overflow: hidden;
        border: solid 1px #72b22a;
        .title {
          color: #fff;
          background: #72b22a;
          display: flex;
          align-items: center;
          padding: 5px 10px;
          .text-img {
            margin-left: auto;
          }
        }
        .content {
          padding: 15px 10px;
          display: flex;
          flex-wrap: wrap;
          .content-group {
            & > div {
              margin-top: 10px;
              & > div {
                margin-top: 8px;
              }
            }
          }
          .submit {
            margin: auto;
            margin-top: 100px;
            width: 100%;
            background: #72b22a;
            color: #fff;
          }
          .submited {
            background: #FAAD14;
            border-color: #FAAD14;
            color: #fff;
            margin: auto;
            margin-top: 100px;
            width: 100%;
          }
          .student {
            display: flex;
            & > :nth-child(1) {
              margin-top: 18px;
            }
            & > :nth-child(2) {
              flex: 1;
              background: #F5F7FA;
              border-radius: 4px;
              padding: 10px 0px 10px 12px;
              display: flex;
              flex-wrap: wrap;
              & > span {
                margin-right: 10px;
              }
            }
          }
        }
      }
    }
    .right {
      width: 758px;
      background: #FFFFFF;
      position: relative;
      height: 100%;
      overflow: auto;
      & > div {
        height: 100%;
        overflow: auto;
        background: #FFFFFF;
      }
    }
    .btns {
      display: flex;
      flex-direction: column;
      .editQuestion, .download {
        width: 40px;
        height: 40px;
        background: #fff;
        border: 1px solid #E4E7ED;
        border-radius: 0 6px 6px 0;
        cursor: pointer;
        text-align: center;
        line-height: 38px;
        &:nth-of-type(2) {
          margin-top: 10px;
        }
      }
    }
  }
</style>
